package com.ctrip.demo.test;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
public class Notice {

    public static <T extends RemindInfo> List<NoticeKV> convert(T t) {
        List<NoticeKV> kvs = new ArrayList<>();
        Class clzz  = t.getClass();
        while(clzz != RemindInfo.class){
            addKvs(kvs, clzz, t);
            clzz = clzz.getSuperclass();
        }
        addKvs(kvs, clzz, t);
        return kvs;
    }


    private static <T extends RemindInfo> void addKvs(List<NoticeKV> kvs, Class clzz, T t){
        for (Field f : clzz.getDeclaredFields()) {
            f.setAccessible(true);
            String k = f.getName();
            if (!Objects.equals(f.getType(), String.class)) {
                log.warn("not support {}. only String", f.getType());
            }
            try {
                if (f.get(t) == null) {
                    continue;
                }
                String v = String.valueOf(f.get(t));
                kvs.add(new NoticeKV(k, v));
            } catch (Exception e) {
                log.error("get value failed.The field is {}", f);
            }
        }
    }

}
